package com.geez.bbl.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;


/**
 * @author biniam.gebremichael
 * @since 12/7/11
 */
public class HeaderFooter extends PdfPageEventHelper {

    Phrase[] header = new Phrase[2];
    int pagenumber = -2;
    boolean skip = true;

    public static Font nyala = FontFactory.getFont(Bbl2Pdf.nyalaFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);


    public void onOpenDocument(PdfWriter writer, Document document) {
        header[0] = new Phrase("");
        header[1] = new Phrase("");
    }

    @Override
    public void onSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) {
        if (depth == 2) {
            skip = true;
        }
        header[depth - 2] = new Phrase(title.getContent(), nyala);
    }

    public Phrase combinedHead() {
        nyala.setColor(BaseColor.DARK_GRAY);
        Phrase phrase = new Phrase(header[0].getContent() + " " + header[1].getContent(),nyala);

        return phrase;
    }

    public void onChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) {
        pagenumber = 1;
    }

    public void onStartPage(PdfWriter writer, Document document) {
        pagenumber++;
    }

    public void onEndPage(PdfWriter writer, Document document) {
        Rectangle rectangle = writer.getBoxSize("art");
        rectangle.setBorder(1);
        rectangle.setBorderWidth(3);
        switch (writer.getPageNumber() % 2) {
            case 0:
                makeHead(writer, rectangle);
                break;
            case 1:
                makeHead(writer, rectangle);
                break;
        }
        String pageNum = pagenumber > 0 ? String.format("%d", pagenumber) : "";
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_CENTER, new Phrase(pageNum, FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL)),
                (rectangle.getLeft() + rectangle.getRight()) / 2, rectangle.getBottom() - 18, 0);
    }

    private void makeHead(PdfWriter writer, Rectangle rectangle) {
        if (!skip) {
            if (pagenumber > 1) {
                ColumnText.showTextAligned(writer.getDirectContent(),
                        Element.ALIGN_CENTER, combinedHead(),
                        (rectangle.getLeft() + rectangle.getRight()) / 2, rectangle.getTop(), 0);
                PdfContentByte cb = writer.getDirectContent();
                cb.setLineWidth(1f);
                cb.setColorStroke(BaseColor.DARK_GRAY);
                cb.setColorFill(BaseColor.DARK_GRAY);
                cb.moveTo(74, 652);
                cb.lineTo(428, 652);
                cb.stroke();
            }
        } else {
            skip = false;
        }
    }
}

